package com.qf.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//抽取公共的servlet
public class baseServlet extends HttpServlet {
    @Override
    //重写service方法
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        //处理post中文乱码
//        request.setCharacterEncoding("utf-8") ;
//        //响应的中文乱码
//        response.setContentType("text/html;charest=utf-8");
        //获取当前类的字节码文件
        Class clazz = this.getClass();
        //创建当前类的实例-->无参构造方法对象

        try {
            Object obj = clazz.newInstance();
            //获取地址栏携带的参数
            // http://localhost:8080/Maven_Project_02_war/子类的模块的地址?methodName=子类的方法名
            //提交方式
            String methodName = request.getParameter("methodName");
            //进行判断
            if (methodName==null){
                //赋值
                methodName="index";
            }
            //然后父类调用子类的方法(向下转型)
            Method method = clazz.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //调用方法
            method.invoke(obj,request,response);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


    }
}
